import 'dart:io';

import 'package:bxultimate/app/router/router_name.dart';
import 'package:bxultimate/data/request/base_request.dart';
import 'package:bxultimate/data/request/user_request.dart';
import 'package:bxultimate/domain/common/MapLatLonDto.dart';
import 'package:bxultimate/domain/common/dict_data.dart';
import 'package:bxultimate/domain/common/result.dart';
import 'package:bxultimate/shared/constant/app_constant.dart';
import 'package:bxultimate/shared/util/util_mk.dart';
import 'package:bxultimate/widgets/app/app_xzqh_select.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/src/components/cell/td_cell.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import 'state.dart';

class UserCompleteInformationController extends GetxController {
  final UserCompleteInformationState state = UserCompleteInformationState();
  MapLatLonDto mapLatLonDto = MapLatLonDto();
  final TextEditingController nameController = TextEditingController();
  final TextEditingController idcardController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController heightController = TextEditingController();
  final TextEditingController weightController = TextEditingController();
  final TextEditingController visionLeftController = TextEditingController();
  final TextEditingController visionRightController = TextEditingController();
  final TextEditingController formerNameController = TextEditingController();
  final TextEditingController unitNameController = TextEditingController();

  var sexDict = <DictData>[];
  var nationDict = <DictData>[];
  var politicsStatusDict = <DictData>[];
  var educationDict = <DictData>[];
  var nativeTypeDict = <DictData>[];
  var religionDict = <DictData>[];
  var isOnlychildDict = <DictData>[];
  var maritalStatusDict = <DictData>[];
  var cylbDict = <DictData>[];

  @override
  onInit() {
    super.onInit();
    SmartDialog.showLoading(msg: '加载信息中');
    getData();
  }

  getData() async {
    // 获取行政区划
    // 初始化字典
    sexDict = await BaseRequest.getDictData("sex");
    nationDict = await BaseRequest.getDictData("nation");
    politicsStatusDict = await BaseRequest.getDictData("politics_status");
    educationDict = await BaseRequest.getDictData("education");
    nativeTypeDict = await BaseRequest.getDictData("native_type");
    religionDict = await BaseRequest.getDictData("religion");
    isOnlychildDict = await BaseRequest.getDictData("is_onlychild");
    maritalStatusDict = await BaseRequest.getDictData("marital_status");
    cylbDict = await BaseRequest.getDictData("cylb");

    state.information = await UserRequest.getUserInformation();
    nameController.text = state.information.name ?? '';
    idcardController.text = state.information.idcard ?? '';
    phoneController.text = state.information.phone ?? '';
    heightController.text = state.information.height ?? '';
    weightController.text = state.information.weight ?? '';
    if (state.information.vision != null) {
      visionLeftController.text = state.information.vision!.split(",")[0];
      visionRightController.text = state.information.vision!.split(",")[1];
    }

    formerNameController.text = state.information.formerName ?? '';
    unitNameController.text = state.information.unitName ?? '';

    SmartDialog.dismiss();
  }

  clearInput(TextEditingController controller) {
    controller.clear();
  }

  void onChange(TextEditingController controller, String text) {
    controller.text = text;
  }

  save() async {
    state.information = state.information.copyWith(
        name: nameController.text,
        idcard: idcardController.text,
        phone: phoneController.text,
        height: heightController.text,
        weight: weightController.text,
        formerName: formerNameController.text,
        unitName: unitNameController.text,
        vision: visionLeftController.text + "," + visionRightController.text);

    Result result = await UserRequest.perfectManyInfo(state.information);
    if (result.code == AppConstant.RESULT_ERROR) {
      SmartDialog.showNotify(
          msg: result.message!, notifyType: NotifyType.failure);
    } else {
      SmartDialog.showNotify(msg: '保存成功', notifyType: NotifyType.success);
      Get.offNamed(RouterName.userInformation);
    }
  }

  void showBirthdayPicker(TDCell cell) {
    var b = state.information.birthday!.split("-");

    TDPicker.showDatePicker(Get.context, title: '选择生日', onConfirm: (selected) {
      state.information = state.information.copyWith(
          birthday:
              '${selected['year'].toString().padLeft(4, '0')}-${selected['month'].toString().padLeft(2, '0')}-${selected['day'].toString().padLeft(2, '0')}');
      Navigator.of(Get.context!).pop();
    }, initialDate: [int.parse(b[0]), int.parse(b[1]), int.parse(b[2])]);
  }

  String getDictLabel(String key) {
    var value;
    switch (key) {
      case 'sex':
        value = state.information.sex;
        if (value == null) return "";
        var index = sexDict
            .indexWhere((element) => int.parse(element.dictValue!) == value);
        if (index == -1) {
          return "";
        }
        return sexDict[index].dictLabel!;
      case 'nation':
        value = state.information.nation;
        if (value == null) return "";
        var index =
            nationDict.indexWhere((element) => element.dictValue == value);
        if (index == -1) {
          return "";
        }
        return nationDict[index].dictLabel!;
      case "politics_status":
        value = state.information.political;
        if (value == null) return "";
        var index = politicsStatusDict
            .indexWhere((element) => element.dictValue == value);
        if (index == -1) {
          return "";
        }
        return politicsStatusDict[index].dictLabel!;
      case "education":
        value = state.information.education;
        if (value == null) return "";
        var index =
            educationDict.indexWhere((element) => element.dictValue == value);
        if (index == -1) {
          return "";
        }
        return educationDict[index].dictLabel!;
      case "native_type":
        value = state.information.hjType;
        if (value == null) return "";
        var index =
            nativeTypeDict.indexWhere((element) => element.dictValue == value);
        if (index == -1) {
          return "";
        }
        return nativeTypeDict[index].dictLabel!;
      case "religion":
        value = state.information.zjxy;
        if (value == null) return "";
        var index = religionDict
            .indexWhere((element) => int.parse(element.dictValue!) == value);
        if (index == -1) {
          return "";
        }
        return religionDict[index].dictLabel!;
      case "isOnlychild":
        value = state.information.isOnlychild;
        if (value == null) return "";
        var index = isOnlychildDict
            .indexWhere((element) => int.parse(element.dictValue!) == value);
        if (index == -1) {
          return "";
        }
        return isOnlychildDict[index].dictLabel!;
      case "marriageStatus":
        value = state.information.marriageStatus;
        if (value == null) return "";
        var index = maritalStatusDict
            .indexWhere((element) => int.parse(element.dictValue!) == value);
        if (index == -1) {
          return "";
        }
        return maritalStatusDict[index].dictLabel!;
      case "cylb":
        value = state.information.cylb;
        if (value == null) return "";
        var index =
            cylbDict.indexWhere((element) => element.dictValue == value);
        if (index == -1) {
          return "";
        }
        return cylbDict[index].dictLabel!;
      default:
        return "";
    }
  }

  void showPicker(String key) {
    switch (key) {
      case 'sex':
        TDPicker.showMultiPicker(Get.context, title: '选择性别',
            onConfirm: (selected) {
          state.information = state.information
              .copyWith(sex: int.parse(sexDict[selected[0]].dictValue!));
          Navigator.of(Get.context!).pop();
        }, data: [sexDict.map((e) => e.dictLabel!).toList()]);
        break;
      case 'nation':
        TDPicker.showMultiPicker(Get.context, title: '选择民族',
            onConfirm: (selected) {
          state.information = state.information
              .copyWith(nation: nationDict[selected[0]].dictValue);
          Navigator.of(Get.context!).pop();
        }, data: [nationDict.map((e) => e.dictLabel!).toList()]);
        break;
      case "politics_status":
        TDPicker.showMultiPicker(Get.context, title: '选择政治面貌',
            onConfirm: (selected) {
          state.information = state.information
              .copyWith(nation: politicsStatusDict[selected[0]].dictValue);
          Navigator.of(Get.context!).pop();
        }, data: [politicsStatusDict.map((e) => e.dictLabel!).toList()]);
        break;
      case "education":
        TDPicker.showMultiPicker(Get.context, title: '选择学历',
            onConfirm: (selected) {
          state.information = state.information
              .copyWith(education: educationDict[selected[0]].dictValue);
          Navigator.of(Get.context!).pop();
        }, data: [educationDict.map((e) => e.dictLabel!).toList()]);
        break;
      case "native_type":
        TDPicker.showMultiPicker(Get.context, title: '选择户籍类别',
            onConfirm: (selected) {
          state.information = state.information
              .copyWith(hjType: nativeTypeDict[selected[0]].dictValue);
          Navigator.of(Get.context!).pop();
        }, data: [nativeTypeDict.map((e) => e.dictLabel!).toList()]);
      case "religion":
        TDPicker.showMultiPicker(Get.context, title: '选择宗教信仰',
            onConfirm: (selected) {
          state.information = state.information
              .copyWith(zjxy: int.parse(religionDict[selected[0]].dictValue!));
          Navigator.of(Get.context!).pop();
        }, data: [religionDict.map((e) => e.dictLabel!).toList()]);
      case "isOnlychild":
        TDPicker.showMultiPicker(Get.context, title: '选择是否独生子女',
            onConfirm: (selected) {
          state.information = state.information.copyWith(
              isOnlychild: int.parse(isOnlychildDict[selected[0]].dictValue!));
          Navigator.of(Get.context!).pop();
        }, data: [isOnlychildDict.map((e) => e.dictLabel!).toList()]);
      case "marriageStatus":
        TDPicker.showMultiPicker(Get.context, title: '选择婚姻状况',
            onConfirm: (selected) {
          state.information = state.information.copyWith(
              marriageStatus:
                  int.parse(maritalStatusDict[selected[0]].dictValue!));
          Navigator.of(Get.context!).pop();
        }, data: [maritalStatusDict.map((e) => e.dictLabel!).toList()]);
      case "cylb":
        TDPicker.showMultiPicker(Get.context, title: '选择从业类别',
            onConfirm: (selected) {
          state.information = state.information
              .copyWith(cylb: cylbDict[selected[0]].dictValue!);
          Navigator.of(Get.context!).pop();
        }, data: [cylbDict.map((e) => e.dictLabel!).toList()]);
    }
  }

  // 地址选择
  void addressSelect() async {
    mapLatLonDto = await Get.toNamed(RouterName.commonMapPointSelect);
    state.information.copyWith(
        address: mapLatLonDto.address,
        lat: mapLatLonDto.lat.toString(),
        lon: mapLatLonDto.lon.toString());
  }

  showJgPicker() {
    UtilMk.openBottomSheet(
        520,
        "籍贯选择",
        AppXzqhSelect(
          level: 3,
          onSelect: (areaCode, areaName) {
            state.information = state.information
                .copyWith(areaXzqh: areaCode, areaXzqhText: areaName);
          },
        ));
  }

  showHjszdPicker() {
    UtilMk.openBottomSheet(
        520,
        "户籍所在地选择",
        AppXzqhSelect(
          level: 4,
          onSelect: (areaCode, areaName) {
            state.information = state.information
                .copyWith(hjszd: areaCode, hjszdText: areaName);
          },
        ));
  }

  void showPicPicker() async {
    showGeneralDialog(
      context: Get.context!,
      pageBuilder: (BuildContext buildContext, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return TDAlertDialog.vertical(
            title: '请选择图片',
            showCloseButton: true,
            buttons: [
              TDDialogButtonOptions(
                  title: '拍摄',
                  action: () async {
                    final AssetEntity? entity =
                        await CameraPicker.pickFromCamera(
                      Get.context!,
                    );
                    if (entity != null) {
                      updateYczHandler(entity);
                    }
                  },
                  theme: TDButtonTheme.primary),
              TDDialogButtonOptions(
                  title: '从手机相册选择',
                  titleColor: TDTheme.of(Get.context).brandColor7,
                  action: () async {
                    final List<AssetEntity>? result =
                        await AssetPicker.pickAssets(Get.context!,
                            pickerConfig: AssetPickerConfig(
                                textDelegate: AssetPickerTextDelegate(),
                                maxAssets: 1,
                                requestType: RequestType.image));
                    if (result != null) {
                      updateYczHandler(result[0]);
                    }
                  },
                  theme: TDButtonTheme.light),
            ]);
      },
    );
  }

  updateYczHandler(AssetEntity assets) async {
    File? file = await assets.file;
    SmartDialog.showLoading(msg: "上传中...");
    var response =
        await BaseRequest.uploadWithBtype(file!.path, "user", "oneInchPhoto");
    state.information = state.information.copyWith(photo: response.path);
    SmartDialog.dismiss();
    Get.back();
  }
}
